package com.zjzywl.smoke.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.websocket.server.PathParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjzywl.smoke.authenticate.AuthUser;
import com.zjzywl.smoke.repository.AuthorityRepository;
import com.zjzywl.smoke.repository.OrganizationRepository;
import com.zjzywl.smoke.repository.RoleRepository;
import com.zjzywl.smoke.repository.SysUserRepository;
import com.zjzywl.smoke.service.OrganizationService;
import com.zjzywl.smoke.service.SysUserService;
import com.zjzywl.smoke.util.RestResult;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.Authority;
import com.zjzywl.smoke.entity.Organization;
import com.zjzywl.smoke.entity.Role;
import com.zjzywl.smoke.entity.SysUser;

import net.sf.json.JSONObject;

@RestController
public class UserActionController extends BaseController {

	@Autowired
	private SysUserRepository repository;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private OrganizationRepository orgRepository;
	@Autowired
	private RoleRepository roleRepository;
	@Autowired
	private AuthorityRepository authorityRepository;
	@Autowired
	private OrganizationService organizationService;

	@RequestMapping(value = "/login")
	public String Login(HttpSession session, Model model, @PathParam("username") String username,
			@PathParam("password") String password) {
		session.setMaxInactiveInterval(-1);
		model.addAttribute("username", username);
		model.addAttribute("password", password);
		if ((username != null) && (username.length() > 0)) {
			model.addAttribute("auto", true);
			session.setAttribute("auto", true);
		} else {
			model.addAttribute("auto", false);
			session.setAttribute("auto", false);
		}

		return "login/login";
	}

	// android登陆接口
	@RequestMapping("/loginPost")

	public WebResult loginPost(HttpServletRequest request, Model model) {
		String loginName = request.getParameter("loginName");
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String password = request.getParameter("password");
		System.out.println(loginName + password);

		SysUser user = repository.findByLoginName(loginName);
		System.out.println(user.getPassword());
		System.out.println(encoder.matches(password, user.getPassword()));
		if (user == null) {
			return WebResult.FAIL("用户名或密码错误");
		} else {
			if (encoder.matches(password, user.getPassword())) {
				model.addAttribute("loginName", loginName);
				model.addAttribute("password", password);
				return WebResult.OK(user.getName());
			} else {
				return WebResult.FAIL("密码错误");
			}
		}
	}

	@RequestMapping("/user")

	public WebResult loginUser(HttpServletRequest request) {
		String loginName = request.getParameter("loginName");

		List<String> user = repository.findUser(loginName);

		return WebResult.OK(user);

	}

	/*
	 * 添加,修改用户
	 */
	@PostMapping(value = "/user/save/{orgid}/{roleId}")

	public ResponseEntity<SysUser> add(@RequestBody SysUser sysUser, @PathVariable("orgid") Integer orgid,
			@PathVariable("roleId") Integer roleId) {

		Organization org = orgRepository.findOne(orgid);
		if (org == null) {
			return RestResult.notFound("找不到编号为" + orgid + "的组织!");
		}

		// 新增用户
		if (sysUser.getUserId() == null) {
			sysUser.setUserType(1);
		} else {
			// 若修改超级用户的权限
			if (repository.findOne(sysUser.getUserId()).getUserType() == 0 && sysUser.getPower().equals("1")) {
				return RestResult.notFound("不能将本账户权限改为操作员!");
			}
		}
		Role findOne = roleRepository.findOne(roleId);
		// 将SysUser和Role相关联
		sysUser.setRole(findOne);

		// 1、判断是否是新增用户，新增用户执行密码加密操作
		// 2、老用户判断是否修改密码，修改密码需要加密
		if ((sysUser.getUserId() == null)
				|| (!repository.findOne(sysUser.getUserId()).getPassword().equals(sysUser.getPassword()))) {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			sysUser.setPassword(encoder.encode(sysUser.getPassword().trim()));
		}

		sysUser.setOrg(org);

		return RestResult.OK(repository.save(sysUser));
	}

	// 添加角色，为角色赋权
	@RequestMapping(value = "/add/role")
	public WebResult addRole(@PathParam("roleName") String roleName, @PathParam("manage") String manage,
			@PathParam("fireAlarm") String fireAlarm, @PathParam("front") String front) {
		// 添加角色
		Role role = new Role();
		role.setName(roleName);
		roleRepository.save(role);
		// 角色赋权
		Authority authority = new Authority();
		authority.setManage(manage);
		authority.setFireAlarm(fireAlarm);
		authority.setRole(role);
		authority.setFront(front);
		authorityRepository.save(authority);
		return WebResult.OK();

	}

	// 删除账号
	@PostMapping(value = "/user/del/{id}")
	public ResponseEntity<Object> del(@PathVariable("id") Integer id) {
		try {
			SysUser sysUser = repository.findOne(id);
			if (sysUser.getUserType() != null && sysUser.getUserType() == 0) {
				return RestResult.badRequest("不能删除初始化用户!");
			} else {
				repository.delete(id);
				return RestResult.OK();
			}
		} catch (Exception e) {
			return RestResult.badRequest(e.getMessage());
		}
	}

	/*
	 * 查看用户
	 */
	@RequestMapping(value = "/user/data/list")

	public WebResult list() {
		try {
			// 获取当前用户的userType
			AuthUser authUser = getLoginUser();
			Integer userType = authUser.getPeople().getUserType();

			if (userType == 0) {
				return WebResult.OK(repository.findAll());
			} else {
				return WebResult.OK(repository.findByUserTypeNot(0));
			}
		} catch (Exception e) {
			return WebResult.FAIL(e.getMessage());
		}
	}

	@RequestMapping(value = "/user/list")
	public String sysUserList(Model model) {
		List<SysUser> sysUsers = null;
		// 获取当前用户的userType
		AuthUser authUser = getLoginUser();
		Integer userType = authUser.getPeople().getUserType();
		if (userType != 0) {
			sysUsers = repository.findByUserTypeNot(0);
		} else {
			sysUsers = repository.findAll();
		}
		model.addAttribute("sysUsers", sysUsers);

		List<Organization> orgs = orgRepository.findAll();
		model.addAttribute("orgs", orgs);

		return "sysUser/sysUser";
	}

	@RequestMapping(value = "/findByUserTypeNot")
	public List<SysUser> findByUserTypeNot() {
		List<SysUser> findByUserTypeNot = repository.findByUserTypeNot(0);
		return findByUserTypeNot;

	}

	@RequestMapping(value = "/findAll")
	public List<SysUser> findAll() {
		List<SysUser> findAll = repository.findAll();
		return findAll;

	}

	// 查看登陆账号
	@RequestMapping(value = "/user/get/{userId}")
	public ResponseEntity<SysUser> get(@PathVariable("userId") Integer userId) {
		SysUser sysUser = repository.findOne(userId);
		if (sysUser != null) {
			return RestResult.OK(sysUser);
		} else {
			return RestResult.notFound("找不到用户信息");
		}
	}

	@RequestMapping(value = "/user/validateName", method = RequestMethod.POST)

	public String validateName(@RequestParam String loginName, @RequestParam String originalloginName) {
		// 编辑时判定是否为同名，编辑时可同名
		System.out.println("validateName: " + loginName + "," + originalloginName);
		JSONObject obj = new JSONObject();
		obj.put("valid", true);
		if ((originalloginName != null) && originalloginName.length() > 0) {
			// edit the role
			if (loginName.equals(originalloginName))
				return obj.toString();
		}

		// 其他情况均需要数据库判定
		try {
			obj.put("valid", true);
			List<SysUser> sysUsers = repository.findAll();
			// get the Role entity
			for (SysUser su : sysUsers) {
				if (su.getLoginName().equals(loginName)) {
					obj.put("valid", false);
					System.out.println(obj.toString());
				}
			}
		} catch (Exception e) {
			// can not get the Role entity
			obj.put("valid", true);
		}

		return obj.toString();
	}

	@RequestMapping(value = "/user/currentuser")
	public WebResult getCurrentUser() {
		SysUser user = ((AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPeople();
		try {
			if (user != null) {
				return WebResult.OK(user);
			} else {
				return WebResult.FAIL("找不到用户信息");
			}
		} catch (Exception e) {
			// TODO: handle exception
			return WebResult.FAIL(e.getMessage());
		}
	}

	// 获取账号列表，根据path
	@RequestMapping(value = "/get/user/list/{userId}")
	public ResponseEntity<List<SysUser>> getCurrentUser(@PathVariable("userId") Integer userId) {
		SysUser user = sysUserService.findOne(userId);
		Organization org = user.getOrg();
		String path = org.getPath();
		List<SysUser> users = repository.getUserByPath(path + "%");
		return RestResult.OK(users);

	}

	// @RequestMapping(value="/loginChecked",method=RequestMethod.POST)
	// public String loginChecked(Model model,HttpSession session,
	// @RequestParam("username") String username,@RequestParam("password") String
	// password) throws Exception {
	//
	// try {
	// if (repository.findByLoginNameAndPassword(username,
	// password)!=null)//(username.equals("admin") && password.equals("123456"))
	// {
	// session.setAttribute("login","ok");
	// return "redirect:/";
	// }
	// else
	// {
	// session.setAttribute("login","");
	// model.addAttribute("logret", "登录失败！");
	// return "login/login";
	// }
	// } catch (Exception e) {
	// session.setAttribute("login","");
	// return "redirect:/login";
	// }
	//
	// }

	// @RequestMapping(value="/logout")
	// public String logout(Model model,HttpSession session) {
	// session.setAttribute("login","");
	// model.addAttribute("logret", "登录失败！");
	// return "login/login";
	// }

}
